﻿using RuoVea.ExDto;
using RuoVea.ExUtil;
using RuoVea.QuartzNetUI.Entitys;
using RuoVea.QuartzNetUI.Server.Dto;
using SqlSugar;

namespace RuoVea.QuartzNetUI.Server.Impl
{
    /// <summary>
    /// 任务日志服务
    /// </summary>
    public class TaskLogService : ITaskLogService
    {
        private readonly ISqlSugarClient _sqlSugarClient;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sqlSugarClient"></param>
        public TaskLogService(ISqlSugarClient sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient;
        }

        /// <summary>
        /// 添加任务日志
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<RestfulResult> InsertAsync(TaskLog data)
        {
            RestfulResult restfulResult = new RestfulResult() { Code = ExEnum.CodeStatus.OK };
            try
            {
                if (data.JobId == null)
                    throw new ArgumentException($"{nameof(data.JobId)} 数据不能为空.");

                if (data.Result?.Length > 4000) { data.Result = data.Result.Substring(0, 4000); }
                if (data.Exception?.Length > 4000) { data.Exception = data.Exception.Substring(0, 4000); }
                if (data.Parameters?.Length > 4000) { data.Parameters = data.Parameters.Substring(0, 4000); }

                data.Id = ExIdGen.IdGenerator.Id;
                //获取任务信息
                var firstData = await _sqlSugarClient.Queryable<TaskDetail>().Where(f => f.Id == data.JobId).FirstAsync();
                if (firstData != null)
                {
                    data.JobId = data.JobId;
                    data.JobName = firstData.JobName;
                    data.JobGroup = firstData.JobGroup;
                    data.CreateTime = DateTime.Now;
                }
                var returnData = await _sqlSugarClient.Insertable(data).IgnoreColumns(true).ExecuteCommandAsync();
                restfulResult.Data = returnData;
            }
            catch (Exception ex)
            {
                restfulResult.Code = ExEnum.CodeStatus.BadRequest;
                restfulResult.Message = ex.Message;
                ("添加任务日志" + ex.Message).WriteErrorLine();
            }
            return restfulResult;
        }

        /// <summary>
        /// 获取任务日志
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<RestfulResult<IList<TaskLog>>> GetTaskLogListAsync(TaskLogQueryDto data)
        {
            RestfulResult<IList<TaskLog>> restfulResult = new RestfulResult<IList<TaskLog>>();
            try
            {
                var BeginTime = ( DateTime.Now).AddDays(-7);
                var EndTime = (DateTime.Now).AddDays(7);

                var TaskLogs = await _sqlSugarClient.Queryable<TaskLog>()
                        .Where(x => x.CreateTime >= BeginTime && x.CreateTime <= EndTime)
                        .WhereIF(data.JobId != null, x => x.JobId == data.JobId)
                        .WhereIF(string.IsNullOrWhiteSpace(data.JobName), x => x.JobName.Contains(data.JobName))
                        .WhereIF(string.IsNullOrWhiteSpace(data.JobGroup), x => x.JobGroup.Contains(data.JobGroup))
                        .ToListAsync();
                restfulResult.Data = TaskLogs;
            }
            catch (Exception ex)
            {
                restfulResult.Code = ExEnum.CodeStatus.BadRequest;
                restfulResult.Message = ex.Message;
            }
            return restfulResult;
        }

        /// <summary>
        /// 获取任务日志
        /// </summary>
        /// <param name="data"></param>
        /// <returns> </returns>
        public async Task<RestfulResult<PageResult<TaskLog>>> GetTaskLogPageListAsync(TaskLogPageDto data)
        {
            RestfulResult<PageResult<TaskLog>> restfulResult = new RestfulResult<PageResult<TaskLog>> { Code = ExEnum.CodeStatus.OK };
            try
            {
                PageResult<TaskLog> pageResult = new PageResult<TaskLog>(data.PageNo, data.PageSize);
                
                data.BeginTime = (data?.BeginTime ?? DateTime.Now).AddDays(-7);
                data.EndTime = (data?.EndTime ?? DateTime.Now).AddDays(7);
                RefAsync<int> totalNumber = 0;

                pageResult.Rows = await _sqlSugarClient.Queryable<TaskLog>()
                    .Where(x => x.Deleted == ExEnum.IsDelete.N)
                    .Where(x => x.CreateTime >= data.BeginTime && x.CreateTime <= data.EndTime)
                    .WhereIF(data.Filter != null && data.Filter.JobId != null && data.Filter.JobId != 0, x => x.JobId == data.Filter.JobId)
                         //.WhereIF(string.IsNullOrWhiteSpace(data.Filter.SchedName), x => x.SchedName == data.Filter.SchedName)
                         .WhereIF(data.Filter != null && !string.IsNullOrWhiteSpace(data.Filter.JobName), x => x.JobName.Contains(data.Filter.JobName))
                         .WhereIF(data.Filter != null && !string.IsNullOrWhiteSpace(data.Filter.JobGroup), x => x.JobGroup.Contains(data.Filter.JobGroup))
                         .WhereIF(data.Filter!= null && data.Filter.Status != null, x => x.Status==(data.Filter.Status))
                        .OrderByDescending(x=>x.CreateTime)
                         .ToPageListAsync(data.PageNo, data.PageSize, totalNumber);

                pageResult.TotalRows = totalNumber.Value;
                restfulResult.Data = pageResult;
            }
            catch (Exception ex)
            {
                restfulResult.Code = ExEnum.CodeStatus.BadRequest;
                restfulResult.Message = ex.Message;
            }
            return restfulResult;
        }

        /// <summary>
        /// 根据Id列表或者时间区间删除日志
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<RestfulResult> DeleteAsync(TaskLogDeleteDto data)
        {
            RestfulResult restfulResult = new RestfulResult { Code = ExEnum.CodeStatus.OK };
            try
            {
                int restfulResultData = await _sqlSugarClient.Deleteable<TaskLog>()
                    .WhereIF(data.Ids.Count > 0, x => data.Ids.Contains(x.Id))
                    .WhereIF(data.StartTime != null && data.EndTime != null, x => x.CreateTime >= data.StartTime && x.CreateTime <= data.EndTime).ExecuteCommandAsync();
                if (restfulResultData > 0)
                    restfulResult.Message = "删除成功";
                else
                {
                    restfulResult.Code = ExEnum.CodeStatus.BadRequest;
                    restfulResult.Message = "删除失败";
                }
            }
            catch (Exception ex)
            {
                restfulResult.Code = ExEnum.CodeStatus.BadRequest;
                restfulResult.Message = ex.Message;
                ex.Message.WriteErrorLine();
            }
            return restfulResult;
        }
    }
}
